const ReadTable = require('../model/readTable')
const servBook = require("./serveBook")
const {Op} = require("sequelize");
const sequelize = require("sequelize");
const Book = require("../model/book");
const User = require("../model/User");

//添加借阅表,借书
exports.addReadTable= async function(BookId,UserId){
  const status = await exports.findReadTableStatus(UserId,BookId,false);
if(status){
  return null;
}
 console.log("借阅")
  const book = await servBook.updataSum(BookId);
  if(book===null){
    return "该书暂无库存！"
  }
  const result =  await ReadTable.create({
        UserId,
        BookId
    })
  return result;
}
//用户阅读排行
exports.findUserReadTop = async function(){

  const result = await ReadTable.findAll({
    attributes:["UserId",[sequelize.fn("count","BookId"),'count'] ],
    group:"UserId",
    order: sequelize.literal('count DESC'),
    include:{
      attributes:["name"],
      model:User
    },
    limit:10
  })

  return  JSON.parse(JSON.stringify(result))  ;
}
//热门书籍
exports.findTopBook = async function(){
  const result = await ReadTable.findAll({
    attributes:['BookId',[sequelize.fn("count","UserID"),'count']],
    group:'BookId',
    include:{
      attributes:["bookName","imgUrl"],
      model:Book
    },
    order: sequelize.literal('count DESC'),
    limit:10
  })
  return  JSON.parse(JSON.stringify(result))  ;
}
 

exports.findReadTables = async function(){
  const result = await ReadTable.findAll();

  return JSON.stringify(result,null,2);

}
//还书
exports.updataBookStatus = async function(UserId,BookId){
  const status = await exports.findReadTableStatus(UserId,BookId,false);
  if(!status){
    return null;
  }
  const book = await servBook.updataSum(BookId,1);
  if(book === null){
    console.log("book，num添加失败");
    return null
  }
   const result = await ReadTable.update({bookStatus:true},{
     where:{
      UserId,
      BookId,
      bookStatus:false
     }
   })
   console.log("还书结果",result);
  return result;
}
//获取指定用户借阅情况范围的书籍
exports.findUserReadBook = async function(userId,bookStatus=-1,page =1,limit = 10){
  const where ={};
  where.userId = userId;
  // console.log(userId,bookStatus);
  if (bookStatus!==-1) {
    where.bookStatus =bookStatus;
  }
   const result = await ReadTable.findAndCountAll({
     attributes:{exclude:["createdAt",'bookStatus',"UserId","BookId","deletedAt","updatedAt","id"]},
     where,
     include:{
       attributes:['bookName',"id",'author'],
       model:Book
     },
     offset: (page-1) *limit,
     limit
   });
  
   return result;
}
//某用户借的某本书是否归还
exports.findReadTableStatus = async function(UserId,BookId,bookStatus){
      const result = await  ReadTable.findOne({
      where:{
        UserId,
        BookId,
        bookStatus
      }
    });
    return result;//返回借阅表该记录状态
}